//save,get
const express=require('express');
const router=express.Router();
const passport=require("passport");

const Comment=require('../../models/Comment');


//$route  Post api/comments/saveComment
//@desc   return state
//@access private
router.post("/saveComment",passport.authenticate("jwt",{session:false}),(req,res)=>{
    let comment=new Comment({
        user:req.user.id,
        post:req.body.post,
        content:req.body.content,
    })
    comment.save((err)=>{
        if(err){
            res.json({"ok":1});
        }
        else{
            res.json({"ok":0});
        }
    })
})

//$route  Post api/comments/getComments
//@desc   return comments
//@access public
router.post('/getComments',(req,res)=>{
    let post=req.body.post;
    Comment.find({'post':post})
    .sort({'date':-1})
    .populate([{'path':'user','select':'name avatar'}])
    .exec((err,comments)=>{
        if(err){
            res.json({'ok':1,'data':[]});
        }
        else{
            res.json({'ok':0,'data':comments});
        }
    })
})


module.exports=router;